import { computed, reactive, ref, toRaw, UnwrapRef } from 'vue'
import { useHttpRequest } from '@/api/chunfeng/apiRequest'
import { Form, message } from 'ant-design-vue'
import { AddPriceParam, ProductPriceData } from '@/api/chunfeng/sale/price/interfaces'
import { usePriceApi } from '@/api/chunfeng/sale/price'
import { useProductApi } from '@/api/chunfeng/product'
import { ProductData, ProductUnitData } from '@/api/chunfeng/product/interfaces'
import moment from 'moment'
import { SimpleUnitData } from '@/api/chunfeng/unit/interfaces'
import { SimpleCategoryData } from '@/api/chunfeng/category/interfaces'
import { SimpleBrandData } from '@/api/chunfeng/brand/interfaces'

const { executeCommandRequest, executeQueryRequest } = useHttpRequest()
const { queryProductPrice, batchAddPrice } = usePriceApi()
const { queryProduct, queryProductUnit } = useProductApi()

export const usePriceAddFunctions = () => {
  const priceGroupRef = reactive({
    groupId: '',
  })

  interface ProductPriceParam {
    key: string
    editable: boolean
    productId: string
    productName: string
    brandName: string
    unitId: string
    unitName: string
    price: number
  }

  interface ProductInfo {
    uid: string
    name: string
    category: SimpleCategoryData
    brand: SimpleBrandData
    primaryUnit: SimpleUnitData
    enabled: boolean
    description?: string
    disabled: boolean
  }

  interface ProductUnitInfo {
    uid: string
    name: string
    enabled: boolean
    isPrimary: boolean
  }

  const allProducts = reactive<Array<ProductInfo>>([])
  const allOriginalProducts = reactive<Array<ProductInfo>>([])
  const productPriceParams = reactive<Array<ProductPriceParam>>([])

  function loadAllProducts() {
    executeQueryRequest(queryProduct({ enabled: true }), (data: ProductData[]) => {
      allProducts.length = 0
      const productInfos = data.map((value) => ({ disabled: false, ...value }))
      allProducts.push(...productInfos)
      allOriginalProducts.length = 0
      allOriginalProducts.push(...productInfos)
    })
  }

  loadAllProducts()

  function loadProductPrice(groupId: string) {
    executeQueryRequest(
      queryProductPrice({ groupId, enabled: true }),
      (data: ProductPriceData[]) => {
        editingKey.value = ''
        productPriceParams.length = 0
        const existData: ProductPriceParam[] = data.map((value) => ({
          key: moment().format('x'),
          editable: false,
          productId: value.productId,
          productName: value.productName,
          brandName: value.brandName,
          unitId: value.unitId,
          unitName: value.unitName,
          price: value.price,
        }))
        const existIds = existData.map((value) => value.productId)

        allProducts.forEach((value) => {
          value.disabled = existIds.includes(value.uid)
        })
        // sortAllProducts()
        productPriceParams.push(...existData)
      },
    )
  }

  function priceGroupSelected(groupId: string) {
    priceGroupRef.groupId = groupId
    loadProductPrice(groupId)
  }

  const rules = reactive({
    groupId: [
      {
        required: true,
        message: '请选择价格组',
      },
    ],
  })

  const priceColumns = [
    {
      title: '商品',
      dataIndex: 'productName',
      key: 'productName',
      slots: { customRender: 'productId' },
      width: '20%',
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
      key: 'brandName',
      width: '20%',
    },
    {
      title: '单位',
      dataIndex: 'unitName',
      key: 'unitName',
      slots: { customRender: 'unitId' },
      width: '20%',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      slots: { customRender: 'price' },
      width: '20%',
    },
    {
      title: '操作',
      key: 'action',
      slots: { customRender: 'action' },
    },
  ]

  const { validate, resetFields, validateInfos } = Form.useForm(priceGroupRef, rules)

  const editingKey = ref('')
  const fetching = ref(false)

  let productSearchResult: UnwrapRef<Record<string, Array<ProductData>>> = reactive({})
  let unitSearchResult: UnwrapRef<Record<string, Array<ProductUnitInfo>>> = reactive({})

  function searchProduct(value: string) {
    if (value) {
      fetching.value = true
      console.log(`search value [${value}]`)
      productSearchResult[editingKey.value] = []
      executeQueryRequest(queryProduct({ name: value }), (data: ProductData[]) => {
        console.log(`search result for [${value}]:[${JSON.stringify(data)}]`)
        productSearchResult[editingKey.value].push(...data)
        fetching.value = false
      })
    }
  }

  function addNewLine() {
    const key = moment().format('x')
    const newData: ProductPriceParam = {
      key: key,
      editable: true,
      productId: '',
      productName: '',
      brandName: '',
      unitId: '',
      unitName: '',
      price: 0.0,
    }
    if (!editingKey.value || save(editingKey.value)) {
      editingKey.value = key
      productPriceParams.push(newData)
    }
  }

  function remove(key: string) {
    const removed = productPriceParams.filter((value) => value.key === key)[0]
    if (removed.productId) {
      allProducts.filter((value) => value.uid === removed.productId)[0].disabled = false
      // sortAllProducts()
    }
    const data = productPriceParams.filter((value) => value.key !== key)
    productPriceParams.length = 0
    productPriceParams.push(...data)
    if (key === editingKey.value) editingKey.value = ''
  }

  function sortAllProducts() {
    allProducts.sort((a, b) => (a.disabled ? 1 : -1))
  }

  function edit(key: string) {
    if (!editingKey.value) {
      editingKey.value = key
    } else {
      message.info('请先保存正在编辑的数据')
    }
  }

  const checkGroupSelected = computed(() => !!priceGroupRef.groupId)

  let currentProduct: ProductInfo

  function productSelected(productId: string, option: any) {
    // updateProductDisabled(productId, true)
    // sortAllProducts()

    currentProduct = toRaw(allProducts.filter((value) => value.uid === productId)[0])
    const currentProductPriceParam = productPriceParams.filter(
      (value) => value.key === editingKey.value,
    )[0]
    currentProductPriceParam.productName = currentProduct.name
    currentProductPriceParam.brandName = currentProduct.brand.name

    executeQueryRequest(queryProductUnit(productId), (data: ProductUnitData[]) => {
      const units = data.map((value) => ({ isPrimary: value.isPrimary, ...value.unit }))
      unitSearchResult[editingKey.value] = []
      unitSearchResult[editingKey.value].push(...units)
    })
  }

  // function updateProductDisabled(productId: string, disabled: boolean) {
  //   if (productId) {
  //     allProducts.filter((value) => value.uid === productId)[0].disabled = disabled
  //   }
  // }

  function unitSelected(unitId: string) {
    const selectedUnit = unitSearchResult[editingKey.value].filter(
      (value) => value.uid === unitId,
    )[0]
    const currentProductPriceParam = productPriceParams.filter(
      (value) => value.key === editingKey.value,
    )[0]
    if (
      productPriceParams.filter(
        (value) =>
          value.unitId === unitId &&
          currentProduct.uid === value.productId &&
          value.key !== editingKey.value,
      ).length > 0
    ) {
      message.info(`该商品[${currentProduct.name}]单位[${selectedUnit.name}]价格已存在`)
      currentProductPriceParam.unitId = ''
      return
    }
    currentProductPriceParam.unitName = selectedUnit.name
  }

  function add() {
    if (editingKey.value) {
      message.info('请先保存价格数据')
      return
    }

    validate().then(() => {
      executeCommandRequest(batchAddPrice(buildAddPriceParams()), {
        message: '添加价格成功',
        callback: () => {
          resetFields()
          productPriceParams.length = 0
          productSearchResult = {}
          unitSearchResult = {}
        },
      })
    })
  }

  function buildAddPriceParams(): AddPriceParam[] {
    return productPriceParams
      .filter((value) => value.editable)
      .map((value) => ({ groupId: priceGroupRef.groupId, ...value }))
  }

  function save(key: string): boolean {
    let result = false
    const record = productPriceParams.filter((value) => value.key === key)[0]
    let error = false
    if (!record.productId) {
      message.info('请先选择商品')
      error = true
    }
    if (!record.unitId) {
      message.info('请选择单位')
      error = true
    }

    if (!error) {
      editingKey.value = ''
      result = true
    }
    return result
  }

  const customerIdRef = ref('')
  function customerSelected(customerId: string) {
    customerIdRef.value = customerId
  }

  return {
    productPriceParams,
    add,
    rules,
    validateInfos,
    resetFields,
    priceGroupSelected,
    priceColumns,
    addNewLine,
    editingKey,
    searchProduct,
    productSearchResult,
    remove,
    edit,
    save,
    productSelected,
    unitSearchResult,
    unitSelected,
    fetching,
    allProducts,
    checkGroupSelected,
    customerSelected,
  }
}
